<style scoped>
.g-price {
    color: red;
}
.goods-item {
    display: flex;
    padding: 10px 0;
}
.goods-image img {
    width: 100px;
    height: 100px;
    border-radius: 4px;
}
.g-count button {
    border: solid 1px #ddd;
    height: 26px;
    width: 24px;
    line-height: 24px;
    text-align: center;
    color: #666;
    border-radius: 0;
    padding: 0;
}
.g-count input {
    border: none;
    width: 30px;
    border-top: solid 1px #ddd;
    border-bottom: solid 1px #ddd;
    height: 22px;
    line-height: 20px;
    text-align: center;
    border-radius: 0;
}
.g-count {
    display: flex;
}
.checked {
    padding: 0 10px;
    display: flex;
    align-items: center;
}
.goods-info {
    padding: 0 10px;
    display: flex;
    flex-direction: column;
}
.g-title {
    text-align: justify;
    margin-bottom: 10px;
    flex: 1;
}
.page {
    padding: 50px 0 100px;
}
</style>
<template>
    <div class="page">
        <van-nav-bar
            title="购物车"
            left-text="返回"
            left-arrow
            :fixed="true"
            @click-left="$router.back()"
        />
        <div class="goods-list">
            <div class="goods-item" v-for="g in goodsArray" :key="g.id">
                <div class="checked">
                    <van-checkbox v-model="g.checked"></van-checkbox>
                </div>
                <div class="goods-image">
                    <img :src="g.picture" />
                </div>
                <div class="goods-info">
                    <div class="g-title">{{ g.title }}</div>
                    <div class="row">
                        <div class="float-left g-price">
                            ￥ <span class="price-text">{{ (g.add_price / 100).toFixed(2) }}</span>
                        </div>
                        <div class="float-right g-count">
                            <button @click="jian(g)">-</button>
                            <input readonly type="text" v-model="g.count" />
                            <button @click="jia(g)">+</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <van-submit-bar
            :price="totalPrice"
            style="bottom: 50px;"
            button-text="结算"
            @submit="onSubmit"
        />
    </div>
</template>

<script>
import { Dialog } from "vant";
import api from "../components/api";
export default {
    data() {
        return {
            goodsArray: [],
            uid: 0,
        };
    },
    // 开始读取数据
    mounted() {
        // 判断是否已经登录
        if (!sessionStorage.getItem("userinfo")) {
            // 没有登录信息 直接跳转到登录
            Dialog.alert({
                title: "提示",
                message: "您还没有登录,请先登录",
            }).then(() => {
                // 直接替换当前页面未登录页面
                this.$router.replace("/login");
            });
            return;
        } else {
            // 已经登录 则获取用户信息
            const userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
            this.uid = userinfo.id; // 取得用户id并存储
            // 开始加载购物车数据
            this.loadCartData();
        }
    },
    computed:{
        // 计算属性 - 总价
        totalPrice(){
            let totalPrice = 0;
            this.goodsArray.forEach(g=>{
                if(g.checked){
                    totalPrice += g.price * g.count; // 计算每个商品的价格
                }
            })
            return totalPrice;
        }
    },
    methods: {
        jian(g) {
            if (g.count <= 1) {
                // 数量不允许小于1
                return;
            }
            api.get(
                "/carts/update?uid=" + this.uid + "&gid=" + g.id + "&act=jian"
            )
                .then((ret) => {
                    if (ret.code == 0) { // 后端更新 
                        g.count --; // 更新前端数据
                    }
                })
                .catch((err) => console.log(err));
        },
        jia(g) {
            if (g.count >= g.stock) {
                // 数量不允许大于库存
                return;
            }
            api.get(
                "/carts/update?uid=" + this.uid + "&gid=" + g.id + "&act=add"
            )
                .then((ret) => {
                    if (ret.code == 0) { // 后端更新 
                        g.count ++; // 更新前端数据
                    }
                })
                .catch((err) => console.log(err));
        },
        // 加载数据
        loadCartData() {
            api.get("/carts/all?uid=" + this.uid)
                .then((result) => {
                    if (result.code == 0) {
                        // 判断数据是否正常
                        this.goodsArray = result.data;
                    }
                })
                .catch((err) => {
                    Dialog.alert({
                        title: "提示",
                        message: "读取购物车数据失败",
                    });
                });
        },
        onSubmit() {
            const gs = []
            this.goodsArray.forEach(g=>{
                if(g.checked){
                    gs.push({
                        id:g.id,
                        count:g.count
                    })
                }
            })
            this.$router.push('/submit-order?from=carts&goods=' + JSON.stringify(gs))
        },
    },
};
</script>
